//
// Created by zhupi on 2024/11/2.
//

#include "edit_library_dialog.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QGroupBox>

namespace {
    const int BUTTON_WIDTH = 120;
    const int BUTTON_HEIGTH = 24;
}


EditLibraryDialog::EditLibraryDialog(QWidget *parent) : QDialog(parent)
{

}

void EditLibraryDialog::Initial()
{
    QVBoxLayout *mainVbox = new QVBoxLayout(this);
    tabWidget_  = new QTabWidget(this);
    mainVbox->addWidget(tabWidget_);

    InitMaterial();

//    tabWidget_->addTab(new QWidget, "Edit test");

    // 底部两个按钮
    InitButtom(mainVbox);
    this->setLayout(mainVbox);
}

void EditLibraryDialog::InitTop()
{

}

void EditLibraryDialog::InitMaterial()
{
    QWidget *material = new QWidget(tabWidget_);
    QVBoxLayout *mainVbox = new QVBoxLayout;

    // 顶部的group
    QGroupBox *groupBox = new QGroupBox("Search Parameters", this);
    mainVbox->addWidget(groupBox);
    InitSearch(groupBox);

    tableWidget_ = new QTableWidget(tabWidget_);
    SetTableWidget();
    mainVbox->addWidget(tableWidget_);

    InitTableButton(mainVbox);
    material->setLayout(mainVbox);

    tabWidget_->addTab(material, "Edit Library");
}


void EditLibraryDialog::InitTableButton(QVBoxLayout *mainVbox)
{
    QHBoxLayout *buttonHbox = new QHBoxLayout(this);
    // 四个按钮
    QPushButton *viewEdit = new QPushButton("View/Edit Material");
    viewEdit->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(viewEdit, &QPushButton::clicked, [&](){
        std::vector<QString> data;
        GetSelectRow(data);
        emit RowSelectedSg("view", data);
    });
    buttonHbox->addWidget(viewEdit);

    QPushButton *addMaterial = new QPushButton("Add Material");
    addMaterial->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(addMaterial, &QPushButton::clicked, [&](){
        std::vector<QString> data;
        GetSelectRow(data);
        emit RowSelectedSg("add", data);
    });
    buttonHbox->addWidget(addMaterial);

    QPushButton *cloneButton = new QPushButton("Clone Material");
    cloneButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(cloneButton, &QPushButton::clicked, [&](){
        std::vector<QString> data;
        GetSelectRow(data);
        emit RowSelectedSg("clone", data);
    });
    buttonHbox->addWidget(cloneButton);

    QPushButton *removeButton = new QPushButton("Export Material");
    removeButton->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(removeButton, &QPushButton::clicked, [&](){
        std::vector<QString> data;
        GetSelectRow(data);
        emit RowSelectedSg("export", data);
    });
    buttonHbox->addWidget(removeButton);
    mainVbox->addLayout(buttonHbox);
}

void EditLibraryDialog::SetTableWidget()
{
//    tableWidget_->verticalHeader()->setVisible(false);  // 去除左边的序号
    tableWidget_->setSelectionBehavior(QAbstractItemView::SelectRows);  // 选中整行
    tableWidget_->setEditTriggers(QAbstractItemView::NoEditTriggers);   // 禁止编辑单元格
    connect(tableWidget_, &QTableWidget::itemClicked, this, &EditLibraryDialog::ItemClicked);
    tableWidget_->horizontalHeader()->setSortIndicatorShown(true);        // 显示排序指示器
    tableWidget_->horizontalHeader()->setSectionsClickable(true);       // 允许点击表头

    connect(tableWidget_->horizontalHeader(), &QHeaderView::sectionClicked, this, &EditLibraryDialog::HeaderClicked);
//    tableWidget_->setTableSize(10, 10);  // 设置为10行10列
//    tableWidget_->horizontalHeader()->setStyleSheet("background-color: #A9A9A9; font-weight: bold;");  // 设置表头浅灰色
//    tableWidget_->setHorizontalHeaderLabels(QStringList() << "Name" << "Value" << "Unit" << "Evaluated...");
}

void EditLibraryDialog::GetSelectRow(std::vector<QString> &data)
{
    // 获取当前选中的行
    int row = tableWidget_->currentRow();
    if (row >= 0) {  // 如果当前行有效
//        std::vector<QString> rowData;
        for (int col = 0; col < tableWidget_->columnCount(); ++col) {
            data.push_back(tableWidget_->item(row, col)->text());
        }
//        emit RowSelectedSg(rowData);  // 发送信号，传递行数据
    }
}

void EditLibraryDialog::InitSearch(QGroupBox *groupBox)
{
    QVBoxLayout *layout = new QVBoxLayout(groupBox);

    // 搜索框
    searchBox = new QLineEdit(this);
    completer = new QCompleter(this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    searchBox->setCompleter(completer);

    // 下拉框用于选择列
    columnSelector = new QComboBox(this);
    columnSelector->addItem("Name");
    columnSelector->addItem("Location");
    columnSelector->addItem("Origin");
    // ...添加更多列名称

    connect(searchBox, &QLineEdit::textChanged, this, &EditLibraryDialog::onSearchTextChanged);
    connect(completer, QOverload<const QString &>::of(&QCompleter::activated), this, &EditLibraryDialog::onCompleterActivated);

    layout->addWidget(searchBox);
    layout->addWidget(columnSelector);
    groupBox->setLayout(layout);
}

void EditLibraryDialog::InitButtom(QVBoxLayout *mainVbox)
{
    QHBoxLayout *hbox = new QHBoxLayout;
    QPushButton * buttonOk = new QPushButton("确定", this);
    buttonOk->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(buttonOk, &QPushButton::clicked, this, &EditLibraryDialog::OKSg);

    QPushButton * buttoncancel = new QPushButton("取消", this);
    buttoncancel->setFixedSize(BUTTON_WIDTH, BUTTON_HEIGTH);
    connect(buttoncancel, &QPushButton::clicked, this, &EditLibraryDialog::CancelSg);
    hbox->addStretch();
    hbox->addWidget(buttonOk);
    hbox->addWidget(buttoncancel);

    mainVbox->addLayout(hbox);
}


// -------------------------test-------------------
//
//#include <QTableWidget>
//#include <QLineEdit>
//#include <QCompleter>
//#include <QVBoxLayout>
//#include <QComboBox>
//#include <QStringListModel>
//#include <vector>
//#include <QTableWidgetItem>
//
//class MyTableWidget : public QWidget {
//Q_OBJECT
//
//public:
//    MyTableWidget(QWidget *parent = nullptr) : QWidget(parent) {
//        QVBoxLayout *layout = new QVBoxLayout(this);
//
//        // 搜索框和列选择器（如上所述）
//        searchBox = new QLineEdit(this);
//        completer = new QCompleter(this);
//        completer->setCaseSensitivity(Qt::CaseInsensitive);
//        searchBox->setCompleter(completer);
//
//        columnSelector = new QComboBox(this);
//        columnSelector->addItem("Name");
//        columnSelector->addItem("Location");
//        columnSelector->addItem("Origin");
//        // ... 添加更多列名称
//
//        connect(searchBox, &QLineEdit::textChanged, this, &MyTableWidget::onSearchTextChanged);
//        connect(completer, QOverload<const QString &>::of(&QCompleter::activated), this, &MyTableWidget::onCompleterActivated);
//
//        layout->addWidget(searchBox);
//        layout->addWidget(columnSelector);
//
//        // 表格
//        tableWidget = new QTableWidget(this);
//        tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
//        layout->addWidget(tableWidget);
//
//        setLayout(layout);
//    }
//
//    void loadTableData(const std::vector<std::pair<int, std::vector<QString>>> &data) {
//        tableWidget->clearContents();
//        tableWidget->setRowCount(data.size());
//        if (data.size() > 0) {
//            tableWidget->setColumnCount(data[0].second.size());
//        }
//
//        for (int i = 0; i < data.size(); ++i) {
//            int id = data[i].first;
//            const std::vector<QString> &rowData = data[i].second;
//
//            for (int j = 0; j < rowData.size(); ++j) {
//                QTableWidgetItem *item = new QTableWidgetItem(rowData[j]);
//                item->setFlags(item->flags() & ~Qt::ItemIsEditable);  // 禁用编辑
//                if (j == 0) {
//                    item->setData(Qt::UserRole, id);  // 将 ID 存储在第一个单元格的 UserRole 中
//                }
//                tableWidget->setItem(i, j, item);
//            }
//        }
//
//        // 更新completer的选项
//        updateCompleterModel();
//    }
//
//    bool updateRowData(int id, const std::vector<QString> &rowData) {
//        for (int row = 0; row < tableWidget->rowCount(); ++row) {
//            QTableWidgetItem *item = tableWidget->item(row, 0);
//            if (item && item->data(Qt::UserRole).toInt() == id) {
//                for (int col = 0; col < rowData.size(); ++col) {
//                    QTableWidgetItem *cellItem = tableWidget->item(row, col);
//                    if (cellItem) {
//                        cellItem->setText(rowData[col]);
//                    } else {
//                        cellItem = new QTableWidgetItem(rowData[col]);
//                        tableWidget->setItem(row, col, cellItem);
//                    }
//                }
//                return true;  // 找到并更新行后返回
//            }
//        }
//        return false;  // 如果没有找到对应 ID 的行，则返回 false
//    }
//
//private slots:
//    void onSearchTextChanged(const QString &text) {
//        int searchColumn = columnSelector->currentIndex();  // 获取选择的列
//        for (int row = 0; row < tableWidget->rowCount(); ++row) {
//            QTableWidgetItem *item = tableWidget->item(row, searchColumn);
//            if (item && item->text().contains(text, Qt::CaseInsensitive)) {
//                tableWidget->setCurrentCell(row, searchColumn);  // 选中第一个匹配项
//                return;
//            }
//        }
//    }
//
//    void onCompleterActivated(const QString &text) {
//        int searchColumn = columnSelector->currentIndex();
//        for (int row = 0; row < tableWidget->rowCount(); ++row) {
//            QTableWidgetItem *item = tableWidget->item(row, searchColumn);
//            if (item && item->text() == text) {
//                tableWidget->setCurrentCell(row, searchColumn);  // 选中匹配项
//                return;
//            }
//        }
//    }
//
//private:
//    void updateCompleterModel() {
//        int searchColumn = columnSelector->currentIndex();
//        QStringList itemList;
//        for (int row = 0; row < tableWidget->rowCount(); ++row) {
//            QTableWidgetItem *item = tableWidget->item(row, searchColumn);
//            if (item) {
//                itemList << item->text();
//            }
//        }
//        itemList.removeDuplicates();  // 去重
//        QStringListModel *model = new QStringListModel(itemList, completer);
//        completer->setModel(model);
//    }
//
//    QLineEdit *searchBox;
//    QCompleter *completer;
//    QComboBox *columnSelector;
//    QTableWidget *tableWidget;
//};
